// API服务文件 - 用于前端与MySQL后端的通信

// API基础URL
const API_BASE_URL = 'http://1.14.72.133:3000/api';

// 错误处理函数
const handleApiError = (error) => {
  console.error('API请求错误:', error);
  if (error.response) {
    // 服务器返回了错误响应
    return { error: error.response.data.error || '服务器错误' };
  } else if (error.request) {
    // 请求已发送但未收到响应
    return { error: '无法连接到服务器，请检查网络连接' };
  } else {
    // 设置请求时发生错误
    return { error: '请求设置错误' };
  }
};

// 健康证API
const healthCardApi = {
  // 获取所有健康证
  async getAllCards() {
    try {
      const response = await fetch(`${API_BASE_URL}/health-cards`);
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '获取健康证失败');
      }
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '获取健康证失败' };
    }
  },

  // 获取健康证索引
  async getCardIndex() {
    try {
      const response = await fetch(`${API_BASE_URL}/health-cards/index`);
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '获取健康证索引失败');
      }
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '获取健康证索引失败' };
    }
  },

  // 获取单个健康证
  async getCard(uniqueId) {
    try {
      const response = await fetch(`${API_BASE_URL}/health-cards/${uniqueId}`);
      if (!response.ok) {
        if (response.status === 404) {
          return { error: '未找到该健康证' };
        }
        const errorData = await response.json();
        throw new Error(errorData.error || '获取健康证失败');
      }
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '获取健康证失败' };
    }
  },

  // 创建健康证
  async createCard(cardData) {
    try {
      console.log("发送创建健康证请求，数据:", JSON.stringify(cardData));
      
      // 处理请求数据，确保base64数据不会被记录到日志
      const logData = {...cardData};
      if (logData.photoData && logData.photoData.length > 100) {
        logData.photoData = logData.photoData.substring(0, 100) + '...';
      }
      if (logData.stampData && logData.stampData.length > 100) {
        logData.stampData = logData.stampData.substring(0, 100) + '...';
      }
      console.log("请求数据概览:", logData);
      
      const response = await fetch(`${API_BASE_URL}/health-cards`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(cardData)
      });
      
      const responseData = await response.json();
      console.log("服务器响应:", response.status, responseData);
      
      if (!response.ok) {
        throw new Error(responseData.error || '创建健康证失败');
      }
      
      return responseData;
    } catch (error) {
      console.error("创建健康证API错误:", error);
      return { error: error.message || '创建健康证失败' };
    }
  },

  // 更新健康证
  async updateCard(uniqueId, cardData) {
    try {
      console.log(`发送更新健康证请求，ID:${uniqueId}, 数据:`, JSON.stringify({...cardData, photoData: '(图片数据已省略)', stampData: '(图片数据已省略)'}));
      
      const response = await fetch(`${API_BASE_URL}/health-cards/${uniqueId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(cardData)
      });
      
      const responseData = await response.json();
      console.log("服务器响应:", response.status, responseData);
      
      if (!response.ok) {
        throw new Error(responseData.error || '更新健康证失败');
      }
      
      return responseData;
    } catch (error) {
      console.error("更新健康证API错误:", error);
      return { error: error.message || '更新健康证失败' };
    }
  },

  // 删除健康证
  async deleteCard(uniqueId) {
    try {
      const response = await fetch(`${API_BASE_URL}/health-cards/${uniqueId}`, {
        method: 'DELETE'
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '删除健康证失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '删除健康证失败' };
    }
  },

  // 批量删除健康证
  async deleteMultipleCards(uniqueIds) {
    try {
      const response = await fetch(`${API_BASE_URL}/health-cards/batch-delete`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ ids: uniqueIds })
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '批量删除健康证失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '批量删除健康证失败' };
    }
  }
};

// 文件上传API
const uploadApi = {
  // 上传照片
  async uploadPhoto(file) {
    try {
      const formData = new FormData();
      formData.append('photo', file);
      
      const response = await fetch(`${API_BASE_URL}/upload/photo`, {
        method: 'POST',
        body: formData
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '上传照片失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '上传照片失败' };
    }
  },

  // 上传base64格式图片
  async uploadBase64Image(base64Data, type = 'photo') {
    try {
      const response = await fetch(`${API_BASE_URL}/upload/base64`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          imageData: base64Data,
          type: type
        })
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '上传图片失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '上传图片失败' };
    }
  },

  // 上传盖章图片
  async uploadStamp(file) {
    try {
      const formData = new FormData();
      formData.append('stamp', file);
      
      const response = await fetch(`${API_BASE_URL}/upload/stamp`, {
        method: 'POST',
        body: formData
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '上传盖章图片失败');
      }
      
      return await response.json();
    } catch (error) {
      console.error(error);
      return { error: error.message || '上传盖章图片失败' };
    }
  }
};

// 将API导出
window.healthCardApi = healthCardApi;
window.uploadApi = uploadApi; 